<?php
namespace app\common\model;
class Coupon extends Base{
    /**
     * 用户领取优惠卷
     * @param  integer $uid  用户ID
     * @param  integer $cid  优惠卷ID
     * @param  string $from [description]
     * @return [type]       [description]
     */
    function accept($uid,$cid,$from){
        $isAccept=model('memberCoupon')->where(['cid'=>$cid,'uid'=>$uid])->count();
        if($isAccept){
            return json('您已经领取过该优惠券了',1);
        }
        $field='title,usable,remark,value,maxs,nums,expire,type';
        $map=['id'=>$cid,'status'=>1,'type'=>0];
        if($from=='buyVip'){
            $map['type']=1;
        }
        $has=$this->read($map,$field);
        if(empty($has)){
            return json('该优惠卷不存在或已删除',1);
        }
        if($has['maxs']>0&&$has['maxs']-$has['nums']<=0){
            return json('该优惠卷已经领完',1);
        }
        $time=time();
        $has['cid']=$cid;
        $has['uid']=$uid;
        $has['s_time']=$time;
        $has['e_time']=$time+$has['expire']*86400;
        $add=model('memberCoupon')->add($has->toArray());
        if(empty($add)){
            return json('系统繁忙、领取失败',1);
        }
        if($has['maxs']>0){
            $this->where(['id'=>$cid])->setInc('nums');
        }
        return json('领取成功!');
    }
}
